package com.example.cloudmusic.home.adapter

import android.os.Handler
import android.os.Looper
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.view.animation.AnimationUtils
import androidx.recyclerview.widget.DiffUtil
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import androidx.viewpager2.widget.ViewPager2
import com.example.cloudmusic.R
import com.example.cloudmusic.databinding.*
import com.example.cloudmusic.home.model.*
import com.example.cloudmusic.utils.FixedGridLayoutManager
import com.example.cloudmusic.utils.GridItemDecoration

/**
 * 首页适配器，负责展示不同类型的内容区块
 * 使用BaseListAdapter实现，支持DiffUtil
 */
class HomeAdapter : BaseListAdapter<HomeItem, RecyclerView.ViewHolder>(HomeDiffCallback()) {
    private var lastPosition = -1

    // 点击监听接口
    interface OnItemClickListener {
        fun onMusicStyleItemClick(position: Int, item: MusicStyle)
        fun onBannerClick(position: Int, item: Banner)
        fun onArtistClick(position: Int, item: Artist)
        fun onMusicClick(position: Int, item: Music)
        fun onRecommendedPlaylistsClick(position: Int, item: Playlist)
        fun onPersonalPlaylistClick(position: Int, item: Playlist)
    }

    var listener: OnItemClickListener? = null

    override fun getItemViewType(position: Int): Int {
        return when (getItem(position)) {
            is HomeItem.RecommendedPlaylistsSection -> HomeItem.TYPE_RECOMMENDED_PLAYLIST
            is HomeItem.BannerSection -> HomeItem.TYPE_BANNER
            is HomeItem.ArtistSection -> HomeItem.TYPE_ARTIST
            is HomeItem.PersonalPlaylistSection -> HomeItem.TYPE_PERSONAL_PLAYLIST
            is HomeItem.MusicStyleSection -> HomeItem.TYPE_MUSIC_STYLE
            is HomeItem.RecommendedMusicsSection -> HomeItem.TYPE_RECOMMENDED_MUSICS
        }
    }

    override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): RecyclerView.ViewHolder {
        val inflater = LayoutInflater.from(parent.context)

        return when (viewType) {
            HomeItem.TYPE_RECOMMENDED_PLAYLIST -> {
                val binding = ItemHorizontalListBinding.inflate(inflater, parent, false)
                RecommendedPlaylistsViewHolder(binding)
            }
            HomeItem.TYPE_BANNER -> {
                val binding = ItemBannerBinding.inflate(inflater, parent, false)
                BannerViewHolder(binding)
            }
            HomeItem.TYPE_ARTIST -> {
                val binding = ItemArtistSectionBinding.inflate(inflater, parent, false)
                ArtistViewHolder(binding)
            }
            HomeItem.TYPE_PERSONAL_PLAYLIST -> {
                val binding = ItemHorizontalListBinding.inflate(inflater, parent, false)
                PersonalPlaylistViewHolder(binding)
            }
            HomeItem.TYPE_MUSIC_STYLE -> {
                val binding = ItemHorizontalListBinding.inflate(inflater, parent, false)
                MusicStyleViewHolder(binding)
            }
            HomeItem.TYPE_RECOMMENDED_MUSICS -> {
                val binding = ItemRecommendationSectionBinding.inflate(inflater, parent, false)
                RecommendedMusicsViewHolder(binding)
            }
            else -> throw IllegalArgumentException("Unknown view type: $viewType")
        }
    }

    override fun onBindViewHolder(holder: RecyclerView.ViewHolder, position: Int) {
        when (holder) {
            is RecommendedPlaylistsViewHolder -> {
                val item = getItem(position) as HomeItem.RecommendedPlaylistsSection
                holder.bind(item)
            }
            is BannerViewHolder -> {
                val item = getItem(position) as HomeItem.BannerSection
                holder.bind(item)
            }
            is ArtistViewHolder -> {
                val item = getItem(position) as HomeItem.ArtistSection
                holder.bind(item)
            }
            is PersonalPlaylistViewHolder -> {
                val item = getItem(position) as HomeItem.PersonalPlaylistSection
                holder.bind(item)
            }
            is MusicStyleViewHolder -> {
                val item = getItem(position) as HomeItem.MusicStyleSection
                holder.bind(item)
            }
            is RecommendedMusicsViewHolder -> {
                val item = getItem(position) as HomeItem.RecommendedMusicsSection
                holder.bind(item)
            }
        }

        // 添加动画效果
        setAnimation(holder.itemView, position)
    }

    private fun setAnimation(view: View, position: Int) {
        if (position > lastPosition) {
            val animation = AnimationUtils.loadAnimation(view.context, R.anim.item_animation_fall_down)
            view.startAnimation(animation)
            lastPosition = position
        }
    }

    override fun setData(newItems: List<HomeItem>) {
        submitList(newItems)
    }

    inner class RecommendedPlaylistsViewHolder(private val binding: ItemHorizontalListBinding) :
        RecyclerView.ViewHolder(binding.root) {

        private val adapter = RecommendedPlaylistsAdapter().apply {
            setOnItemClickListener { position, item ->
                listener?.onRecommendedPlaylistsClick(position, item)
            }
        }

        init {
            binding.rvHorizontal.adapter = adapter
            binding.rvHorizontal.layoutManager = LinearLayoutManager(
                binding.root.context, LinearLayoutManager.HORIZONTAL, false
            )
        }

        fun bind(section: HomeItem.RecommendedPlaylistsSection) {
            binding.layoutTitle.tvTitle.text = section.title
            adapter.submitList(section.playlists)
        }
    }

    inner class BannerViewHolder(private val binding: ItemBannerBinding) :
        RecyclerView.ViewHolder(binding.root) {

        private val adapter = BannerAdapter().apply {
            setOnItemClickListener { position, item ->
                listener?.onBannerClick(position, item)
            }
        }
        private var isForward = true
        private val handler = Handler(Looper.getMainLooper())
        private val SCROLL_INTERVAL = 3000L
        private val INITIAL_DELAY = 2000L

        private val pageChangeCallback = object : ViewPager2.OnPageChangeCallback() {
            override fun onPageScrollStateChanged(state: Int) {
                when (state) {
                    ViewPager2.SCROLL_STATE_DRAGGING -> stopAutoScroll()
                    ViewPager2.SCROLL_STATE_IDLE -> startAutoScroll()
                }
            }
        }

        private val autoScrollRunnable = object : Runnable {
            override fun run() {
                if (adapter.itemCount > 0) {
                    val currentItem = binding.vpBanner.currentItem

                    if (isForward) {
                        if (currentItem >= adapter.itemCount - 1) {
                            isForward = false
                            binding.vpBanner.currentItem = currentItem - 1
                        } else {
                            binding.vpBanner.currentItem = currentItem + 1
                        }
                    } else {
                        if (currentItem <= 0) {
                            isForward = true
                            binding.vpBanner.currentItem = currentItem + 1
                        } else {
                            binding.vpBanner.currentItem = currentItem - 1
                        }
                    }
                }

                handler.postDelayed(this, SCROLL_INTERVAL)
            }
        }

        init {
            with(binding.vpBanner) {
                adapter = this@BannerViewHolder.adapter
                orientation = ViewPager2.ORIENTATION_HORIZONTAL
                registerOnPageChangeCallback(pageChangeCallback)
            }
            startAutoScroll(INITIAL_DELAY)
        }

        private fun startAutoScroll(delayMs: Long = SCROLL_INTERVAL) {
            handler.removeCallbacks(autoScrollRunnable)
            handler.postDelayed(autoScrollRunnable, delayMs)
        }

        private fun stopAutoScroll() {
            handler.removeCallbacks(autoScrollRunnable)
        }

        fun bind(section: HomeItem.BannerSection) {
            binding.vpBanner.currentItem = 0
            isForward = true
            binding.vpBanner.setCurrentItem(0, false)
            stopAutoScroll()
            adapter.submitList(section.items)
            startAutoScroll(INITIAL_DELAY)
        }

        fun onDetached() {
            stopAutoScroll()
            binding.vpBanner.unregisterOnPageChangeCallback(pageChangeCallback)
        }
    }

    inner class ArtistViewHolder(private val binding: ItemArtistSectionBinding) :
        RecyclerView.ViewHolder(binding.root) {

        private val adapter = ArtistAdapter().apply {
            setOnItemClickListener { position, item ->
                listener?.onArtistClick(position, item)
            }
        }

        init {
            binding.rvArtists.adapter = adapter
            binding.rvArtists.layoutManager = LinearLayoutManager(
                binding.root.context, LinearLayoutManager.HORIZONTAL, false
            )
        }

        fun bind(section: HomeItem.ArtistSection) {
            binding.layoutTitle.tvTitle.text = section.title
            adapter.submitList(section.artists)
        }
    }

    inner class PersonalPlaylistViewHolder(private val binding: ItemHorizontalListBinding) :
        RecyclerView.ViewHolder(binding.root) {

        private val adapter = PersonalPlaylistAdapter().apply {
            setOnItemClickListener { position, item ->
                listener?.onPersonalPlaylistClick(position, item)
            }
        }

        init {
            binding.rvHorizontal.adapter = adapter
            binding.rvHorizontal.layoutManager = LinearLayoutManager(
                binding.root.context, LinearLayoutManager.HORIZONTAL, false
            )
        }

        fun bind(section: HomeItem.PersonalPlaylistSection) {
            binding.layoutTitle.tvTitle.text = section.title
            adapter.submitList(section.items)
        }
    }

    inner class MusicStyleViewHolder(private val binding: ItemHorizontalListBinding) :
        RecyclerView.ViewHolder(binding.root) {

        private val adapter = MusicStyleAdapter().apply {
            setOnItemClickListener { position, item ->
                listener?.onMusicStyleItemClick(position, item)
            }
        }

        init {
            binding.rvHorizontal.adapter = adapter
            binding.rvHorizontal.layoutManager = LinearLayoutManager(
                binding.root.context, LinearLayoutManager.HORIZONTAL, false
            )
        }

        fun bind(section: HomeItem.MusicStyleSection) {
            binding.layoutTitle.tvTitle.text = section.title
            adapter.submitList(section.musics)
        }
    }

    inner class RecommendedMusicsViewHolder(private val binding: ItemRecommendationSectionBinding) :
        RecyclerView.ViewHolder(binding.root) {

        private val adapter = MusicAdapter().apply {
            setOnItemClickListener { position, item ->
                listener?.onMusicClick(position, item)
            }
        }

        init {
            val layoutManager = FixedGridLayoutManager(itemView.context, 3)
            val horizontalSpacing = (8 * itemView.context.resources.displayMetrics.density).toInt()
            val verticalSpacing = (4 * itemView.context.resources.displayMetrics.density).toInt()

            val itemDecoration = GridItemDecoration(
                horizontalSpacing = horizontalSpacing,
                verticalSpacing = verticalSpacing,
                rowsPerColumn = 3
            )

            binding.rvSongs.apply {
                this.layoutManager = layoutManager
                setHasFixedSize(true)
                addItemDecoration(itemDecoration)
                adapter = this@RecommendedMusicsViewHolder.adapter
            }
        }

        fun bind(section: HomeItem.RecommendedMusicsSection) {
            binding.layoutTitle.tvTitle.text = section.title
            adapter.submitList(section.musics)
        }
    }

    override fun onViewDetachedFromWindow(holder: RecyclerView.ViewHolder) {
        super.onViewDetachedFromWindow(holder)
        holder.itemView.clearAnimation()

        if (holder is BannerViewHolder) {
            holder.onDetached()
        }
    }

    override fun onFailedToRecycleView(holder: RecyclerView.ViewHolder): Boolean {
        if (holder is BannerViewHolder) {
            holder.onDetached()
        }
        return super.onFailedToRecycleView(holder)
    }

    private class HomeDiffCallback : DiffUtil.ItemCallback<HomeItem>() {
        override fun areItemsTheSame(oldItem: HomeItem, newItem: HomeItem): Boolean {
            // 判断是否是同一个类型的section
            if (oldItem::class != newItem::class) return false

            // 根据类型判断是否是同一个item
            return when {
                oldItem is HomeItem.BannerSection && newItem is HomeItem.BannerSection -> true // 轮播图通常只有一个
                oldItem is HomeItem.RecommendedPlaylistsSection && newItem is HomeItem.RecommendedPlaylistsSection ->
                    oldItem.title == newItem.title
                oldItem is HomeItem.ArtistSection && newItem is HomeItem.ArtistSection ->
                    oldItem.title == newItem.title
                oldItem is HomeItem.PersonalPlaylistSection && newItem is HomeItem.PersonalPlaylistSection ->
                    oldItem.title == newItem.title
                oldItem is HomeItem.MusicStyleSection && newItem is HomeItem.MusicStyleSection ->
                    oldItem.title == newItem.title
                oldItem is HomeItem.RecommendedMusicsSection && newItem is HomeItem.RecommendedMusicsSection ->
                    oldItem.title == newItem.title
                else -> false
            }
        }

        override fun areContentsTheSame(oldItem: HomeItem, newItem: HomeItem): Boolean {
            return when {
                oldItem is HomeItem.BannerSection && newItem is HomeItem.BannerSection ->
                    oldItem.items == newItem.items
                oldItem is HomeItem.RecommendedPlaylistsSection && newItem is HomeItem.RecommendedPlaylistsSection ->
                    oldItem.playlists == newItem.playlists
                oldItem is HomeItem.ArtistSection && newItem is HomeItem.ArtistSection ->
                    oldItem.artists == newItem.artists
                oldItem is HomeItem.PersonalPlaylistSection && newItem is HomeItem.PersonalPlaylistSection ->
                    oldItem.items == newItem.items
                oldItem is HomeItem.MusicStyleSection && newItem is HomeItem.MusicStyleSection ->
                    oldItem.musics == newItem.musics
                oldItem is HomeItem.RecommendedMusicsSection && newItem is HomeItem.RecommendedMusicsSection ->
                    oldItem.musics == newItem.musics
                else -> false
            }
        }
    }
}